#!/bin/bash

# 智能农业后端部署测试脚本
# 用于验证部署是否成功

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
BASE_URL="http://localhost:8080"
TIMEOUT=30

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查服务是否运行
check_service_running() {
    log_info "检查 Docker 服务状态..."
    
    if ! docker-compose ps | grep -q "Up"; then
        log_error "Docker 服务未运行，请先启动服务"
        log_info "运行: ./deploy.sh 或 docker-compose up -d"
        exit 1
    fi
    
    log_success "Docker 服务正在运行"
}

# 等待服务就绪
wait_for_service() {
    log_info "等待服务就绪..."
    
    for i in $(seq 1 $TIMEOUT); do
        if curl -s -f "$BASE_URL/actuator/health" > /dev/null 2>&1; then
            log_success "服务已就绪"
            return 0
        fi
        
        echo -n "."
        sleep 1
    done
    
    echo ""
    log_error "服务启动超时"
    return 1
}

# 测试健康检查
test_health_check() {
    log_info "测试健康检查端点..."
    
    response=$(curl -s "$BASE_URL/actuator/health")
    status=$(echo "$response" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
    
    if [ "$status" = "UP" ]; then
        log_success "健康检查通过: $status"
    else
        log_error "健康检查失败: $status"
        echo "响应: $response"
        return 1
    fi
}

# 测试 API 文档
test_swagger_ui() {
    log_info "测试 API 文档..."
    
    if curl -s -f "$BASE_URL/swagger-ui.html" > /dev/null; then
        log_success "API 文档可访问"
    else
        log_warning "API 文档不可访问"
    fi
}

# 测试作物选项 API
test_crop_api() {
    log_info "测试作物选项 API..."
    
    response=$(curl -s "$BASE_URL/api/crops/options")
    
    if echo "$response" | grep -q "番茄"; then
        log_success "作物选项 API 正常"
    else
        log_error "作物选项 API 异常"
        echo "响应: $response"
        return 1
    fi
}

# 测试用户注册 API
test_register_api() {
    log_info "测试用户注册 API..."
    
    # 生成随机用户名
    username="testuser_$(date +%s)"
    
    response=$(curl -s -X POST "$BASE_URL/api/auth/register" \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"$username\",\"passwordMd5\":\"5d41402abc4b2a76b9719d911017c592\"}")
    
    if echo "$response" | grep -q "success"; then
        log_success "用户注册 API 正常"
    else
        log_warning "用户注册 API 可能异常（可能是用户已存在）"
        echo "响应: $response"
    fi
}

# 测试数据库连接
test_database_connection() {
    log_info "测试数据库连接..."
    
    if docker exec smart-agriculture-mysql mysqladmin ping -h localhost > /dev/null 2>&1; then
        log_success "数据库连接正常"
    else
        log_error "数据库连接失败"
        return 1
    fi
}

# 显示服务信息
show_service_info() {
    log_info "服务信息:"
    echo "  - 后端 API: $BASE_URL"
    echo "  - API 文档: $BASE_URL/swagger-ui.html"
    echo "  - 健康检查: $BASE_URL/actuator/health"
    echo "  - 数据库: localhost:3306"
    echo ""
    
    log_info "Docker 容器状态:"
    docker-compose ps
}

# 主函数
main() {
    log_info "开始测试智能农业后端部署..."
    echo ""
    
    # 执行测试
    check_service_running
    wait_for_service
    test_health_check
    test_swagger_ui
    test_crop_api
    test_register_api
    test_database_connection
    
    echo ""
    log_success "所有测试完成！"
    show_service_info
}

main "$@"
